// 用户相关API接口
import axios from 'axios'
import type { User, LoginUser, RegisterUser, UserProfile, LoginResponse } from '../types/user'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 统一错误处理
    if (error.response?.status === 401) {
      // 未授权，清除token并重定向到登录页
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    console.error('API请求错误:', error)
    return Promise.reject(error)
  }
)

// 用户登录
export const login = async (credentials: LoginUser): Promise<LoginResponse> => {
  const response = await api.post('/auth/login', credentials)
  // 保存token到localStorage
  if (response.data.token) {
    localStorage.setItem('token', response.data.token)
  }
  return response.data
}

// 用户注册
export const register = async (data: RegisterUser): Promise<User> => {
  const response = await api.post('/auth/register', data)
  return response.data
}

// 获取当前用户信息
export const getCurrentUser = async (): Promise<UserProfile> => {
  const response = await api.get('/user/profile')
  return response.data || response
}

// 更新用户信息
export const updateUserProfile = async (data: Partial<UserProfile>): Promise<UserProfile> => {
  const response = await api.put('/user/profile', data)
  return response.data || response
}

// 修改密码
export const changePassword = async (data: {
  currentPassword: string
  newPassword: string
}): Promise<void> => {
  await api.put('/user/password', data)
}

// 上传头像
export const uploadAvatar = async (file: File): Promise<{ avatarUrl: string }> => {
  const formData = new FormData()
  formData.append('file', file)
  const response = await api.post('/user/avatar', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return response.data
}

// 用户登出
export const logout = (): void => {
  localStorage.removeItem('token')
  // 可以添加其他清理逻辑
}

// 获取用户列表（管理员）
export const getUserList = async (params: {
  page?: number
  pageSize?: number
  keyword?: string
  role?: string
  status?: string
}): Promise<{ list: User[], total: number }> => {
  const response = await api.get('/admin/users', { params })
  return response.data
}

// 禁用/启用用户（管理员）
export const updateUserStatus = async (userId: number, status: 'ACTIVE' | 'BANNED'): Promise<void> => {
  await api.put(`/admin/users/${userId}/status`, { status })
}

// 更新用户角色（管理员）
export const updateUserRole = async (userId: number, role: string): Promise<void> => {
  await api.put(`/admin/users/${userId}/role`, { role })
}